package com.wpml.cloud.classroom.handler;


import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.wpml.cloud.classroom.msg.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;


public class NettyWsChannelInboundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger log = LogManager.getLogger(NettyWsChannelInboundHandler.class);


    public static ChannelGroup ALL_CLIENT = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private Map<String, MsgHandler> msgHandlerMap;

    public NettyWsChannelInboundHandler(Map<String, MsgHandler> msgHandlerMap) {
        this.msgHandlerMap = msgHandlerMap;
    }

    /**
     * 从channel缓冲区读数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {

        Channel currentChannel = ctx.channel();
        // 获取客户端传输过来的消息
        String content = frame.text();
        Message<String> message = JSONUtil.toBean(content, new TypeReference<Message<String>>(){}.getType(), false);

//        Message<String> message = JSON.parseObject(content, new TypeReference<Message<String>>(){}.getType());
        MsgHandler msgHandler = msgHandlerMap.get(message.getType());

        if (msgHandler == null) {
            MessageManager.sendMessage(currentChannel, Message.error("500", "消息类型错误"));
        } else {
            msgHandler.handleMsg(message, currentChannel);
        }
    }

    /**
     * 当客户端连接服务端之后（打开连接）
     * 获取客户端的channle，并且放到ChannelGroup中去进行管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("有新客户端连接{},{}", ctx.channel().remoteAddress(), ctx.channel().id().asLongText());
        ALL_CLIENT.add(ctx.channel());
        log.info("当前共有{}个终端连接", ALL_CLIENT.size());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        String channelId = ctx.channel().id().asShortText();
        ALL_CLIENT.remove(ctx.channel());
        log.info("客户端被移除，channelId为{}", channelId);
        log.info("当前共有{}终端连接", ALL_CLIENT.size());
//        UserManager.logout(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("channel exception", cause);
        ctx.channel().close();
        log.info("当前共有{}终端连接", ALL_CLIENT.size());
        ALL_CLIENT.remove(ctx.channel());
    }
}
